package org.wutopia.labcloud.domain.uaa.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.wutopia.labcloud.domain.uaa.controller.vo.input.UserCreateRoleInputVO;
import org.wutopia.labcloud.domain.uaa.controller.vo.input.UserRoleBindAuthoritiesInputVO;
import org.wutopia.labcloud.domain.uaa.controller.vo.output.UserRoleListOutput;
import org.wutopia.labcloud.domain.uaa.controller.vo.output.UserRoleListOutputVO;
import org.wutopia.labcloud.domain.uaa.dao.UserAuthRoleAuthorityRDao;
import org.wutopia.labcloud.domain.uaa.dao.UserAuthRoleDao;
import org.wutopia.labcloud.domain.uaa.dao.entity.UserAuthRole;
import org.wutopia.labcloud.domain.uaa.dao.entity.UserAuthRoleAuthorityR;
import org.wutopia.labcloud.domain.uaa.service.UserRoleService;
import org.wutopia.labcloud.library.common.base.PageInputVO;
import org.wutopia.labcloud.library.common.base.PageOutputVO;

import java.util.ArrayList;
import java.util.List;

@Service
@AllArgsConstructor
public class UserRoleServiceImpl implements UserRoleService {

    private UserAuthRoleDao userAuthRoleDao;

    private UserAuthRoleAuthorityRDao userAuthRoleAuthorityRDao;

    @Override
    public void createRole(UserCreateRoleInputVO vo) {

        UserAuthRole  userAuthRole = new UserAuthRole();

        userAuthRole.setRoleName(vo.getRoleName());

        userAuthRoleDao.insert(userAuthRole);
    }

    @Override
    public void bindAuthority(UserRoleBindAuthoritiesInputVO vo) {
        Long roleId = vo.getRoleId();
        List<Long> authorityIds = vo.getAuthorityIds();

        for(Long aId : authorityIds) {
            UserAuthRoleAuthorityR r = new UserAuthRoleAuthorityR();
            r.setRoleId(roleId);
            r.setAuthorityId(aId);
            userAuthRoleAuthorityRDao.insert(r);
        }
    }

    @Override
    public PageOutputVO<UserRoleListOutputVO> list(PageInputVO vo) {
        PageOutputVO<UserRoleListOutputVO> outputVO = new PageOutputVO<>();

        UserRoleListOutputVO listVO = new UserRoleListOutputVO();

        List<UserRoleListOutput> list  = new ArrayList<>();

        Page<UserAuthRole> page = new Page<>(vo.getPage(), vo.getSize());
        Page<UserAuthRole> userAuthRolePage = userAuthRoleDao.selectPage(page, null);

        List<UserAuthRole> records = userAuthRolePage.getRecords();
        for(UserAuthRole role : records) {
            UserRoleListOutput roleOut = new UserRoleListOutput();
            roleOut.setRoleName(role.getRoleName());
            roleOut.setId(role.getId());
            list.add(roleOut);
        }

        listVO.setList(list);

        outputVO.setData(listVO);
        outputVO.setSize(vo.getSize());
        outputVO.setPage(vo.getPage());
        outputVO.setTotalPage(userAuthRolePage.getPages());
        outputVO.setTotal(userAuthRolePage.getTotal());

        return outputVO;
    }
}
